<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

use app\service\translation\ContentTranslationService;
use app\common\model\Language;

/**
 * 获取翻译内容的模板函数
 */
function trans_content($tableName, $recordId, $fieldName, $language = null)
{
    static $translationService = null;

    if (!$translationService) {
        $translationService = new ContentTranslationService();
    }

    $language = $language ?: get_current_language();

    return $translationService->getTranslatedContent($tableName, $recordId, $fieldName, $language);
}

/**
 * 获取当前语言
 */
function get_current_language()
{
    // 优先级：URL参数 > Session > Cookie > 默认语言
    $language = $_GET['lang'] ?? $_SESSION['language'] ?? $_COOKIE['language'] ?? null;

    if ($language && Language::isValidLanguageCode($language)) {
        return $language;
    }

    // 返回默认语言
    $defaultLang = Language::getDefaultLanguage();
    return $defaultLang ? $defaultLang->code : 'zh_CN';
}

/**
 * 设置当前语言
 */
function set_current_language($languageCode)
{
    if (!Language::isValidLanguageCode($languageCode)) {
        return false;
    }

    $_SESSION['language'] = $languageCode;
    setcookie('language', $languageCode, time() + 86400 * 30, '/'); // 30天过期

    return true;
}

/**
 * 生成语言切换链接
 */
function lang_url($language, $url = null)
{
    if (!$url) {
        $url = $_SERVER['REQUEST_URI'];
    }

    $parsedUrl = parse_url($url);
    parse_str($parsedUrl['query'] ?? '', $queryParams);
    $queryParams['lang'] = $language;

    $newQuery = http_build_query($queryParams);
    return ($parsedUrl['path'] ?? '/') . ($newQuery ? '?' . $newQuery : '');
}

/**
 * 获取启用的语言列表
 */
function get_enabled_languages()
{
    static $languages = null;

    if ($languages === null) {
        $languages = Language::getEnabledLanguages()->toArray();
    }

    return $languages;
}

/**
 * 获取语言名称
 */
function get_language_name($languageCode, $native = false)
{
    $language = Language::getByCode($languageCode);
    if (!$language) {
        return $languageCode;
    }

    return $native ? $language->native_name : $language->name;
}

/**
 * 检查是否为当前语言
 */
function is_current_language($languageCode)
{
    return get_current_language() === $languageCode;
}

/**
 * 获取语言切换器HTML
 */
function render_language_switcher($template = 'default')
{
    $languages   = get_enabled_languages();
    $currentLang = get_current_language();

    if (count($languages) <= 1) {
        return ''; // 只有一种语言时不显示切换器
    }

    $html = '<div class="language-switcher">';

    foreach ($languages as $language) {
        $isActive    = $language['code'] === $currentLang;
        $activeClass = $isActive ? ' active' : '';
        $url         = lang_url($language['code']);

        if ($template === 'dropdown') {
            $html .= "<option value=\"{$language['code']}\"" . ($isActive ? ' selected' : '') . ">{$language['native_name']}</option>";
        } else {
            $html .= "<a href=\"{$url}\" class=\"lang-link{$activeClass}\" data-lang=\"{$language['code']}\">{$language['native_name']}</a>";
        }
    }

    if ($template === 'dropdown') {
        $html = '<select class="language-selector" onchange="window.location.href=lang_url(this.value)">' . $html . '</select>';
    }

    $html .= '</div>';

    return $html;
}

/**
 * 批量翻译数组数据
 */
function trans_array($items, $language = null)
{
    if (empty($items)) {
        return $items;
    }

    $language = $language ?: get_current_language();

    if ($language === 'zh_CN') {
        return $items; // 默认语言直接返回
    }

    $translationService = new ContentTranslationService();
    return $translationService->batchGetTranslatedContent($items, $language);
}

/**
 * 翻译模型对象
 */
function trans_model($model, $language = null)
{
    if (!$model || !method_exists($model, 'toMultiLanguageArray')) {
        return $model;
    }

    $language = $language ?: get_current_language();
    return $model->toMultiLanguageArray($language);
}

/**
 * 获取多语言SEO信息
 */
function get_seo_meta($tableName, $recordId, $language = null)
{
    $language = $language ?: get_current_language();

    $title       = trans_content($tableName, $recordId, 'seo_title', $language);
    $description = trans_content($tableName, $recordId, 'seo_description', $language);
    $keywords    = trans_content($tableName, $recordId, 'seo_keywords', $language);

    return [
        'title'       => $title,
        'description' => $description,
        'keywords'    => $keywords,
    ];
}

/**
 * 输出多语言meta标签
 */
function render_seo_meta($tableName, $recordId, $language = null)
{
    $meta = get_seo_meta($tableName, $recordId, $language);

    $html = '';
    if ($meta['title']) {
        $html .= "<title>{$meta['title']}</title>\n";
    }
    if ($meta['description']) {
        $html .= "<meta name=\"description\" content=\"{$meta['description']}\">\n";
    }
    if ($meta['keywords']) {
        $html .= "<meta name=\"keywords\" content=\"{$meta['keywords']}\">\n";
    }

    // 添加语言相关的meta标签
    $currentLang = get_current_language();
    $html .= "<meta name=\"language\" content=\"{$currentLang}\">\n";
    $html .= "<meta property=\"og:locale\" content=\"{$currentLang}\">\n";

    // 添加alternate语言链接
    $languages = get_enabled_languages();
    foreach ($languages as $language) {
        if ($language['code'] !== $currentLang) {
            $url  = lang_url($language['code']);
            $html .= "<link rel=\"alternate\" hreflang=\"{$language['code']}\" href=\"{$url}\">\n";
        }
    }

    return $html;
}

/**
 * 创建翻译任务（用于手动触发）
 */
function create_translation_job($tableName, $recordId, $fieldName = null, $targetLanguages = null)
{
    $translationService = new ContentTranslationService();

    if ($fieldName) {
        return $translationService->createTranslationJob($tableName, $recordId, $fieldName, $targetLanguages);
    } else {
        // 为所有可翻译字段创建任务
        $configs = \app\common\model\TranslationConfig::getTableConfig($tableName);
        $jobs    = [];

        foreach ($configs as $config) {
            $jobs[] = $translationService->createTranslationJob($tableName, $recordId, $config->field_name, $targetLanguages);
        }

        return $jobs;
    }
}

/**
 * 检查内容是否有翻译
 */
function has_translation($tableName, $recordId, $fieldName, $languageCode)
{
    return \app\common\model\ContentTranslation::getTranslation($tableName, $recordId, $fieldName, $languageCode) !== null;
}

/**
 * 获取翻译完成度
 */
function get_translation_completeness($tableName, $recordId)
{
    $configs = \app\common\model\TranslationConfig::getTableConfig($tableName);
    if (empty($configs)) {
        return 100;
    }

    $totalFields    = count($configs);
    $languages      = get_enabled_languages();
    $totalLanguages = count($languages) - 1; // 减去默认语言

    $totalExpected  = $totalFields * $totalLanguages;
    $totalCompleted = 0;

    foreach ($configs as $config) {
        foreach ($languages as $language) {
            if ($language['code'] === 'zh_CN')
                continue;

            if (has_translation($tableName, $recordId, $config->field_name, $language['code'])) {
                $totalCompleted++;
            }
        }
    }

    return $totalExpected > 0 ? round($totalCompleted / $totalExpected * 100, 2) : 100;
}
